package com.bookcycle.panda.webfront.controller;

import com.bookcycle.panda.webfront.constant.URLConstant;
import com.bookcycle.panda.webfront.util.AESUtil;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

@Controller
public class LockController {
    @RequestMapping(value = "/lock",method = RequestMethod.POST )
    @ResponseBody
    public String lock(@RequestParam("houseId")String houseId,
                       @RequestParam("lockState")String lockState){
        String result="";
        String cmd="";
        if(lockState.equals("true")){
            cmd="open";
        }else {
            cmd="close";
        }

        try {
            RestTemplate restTemplate=new RestTemplate();
            Map<String ,Object> param=new HashMap<String ,Object>();
            param.put("houseId",houseId);
            ResponseEntity<String> responseEntity=restTemplate.getForEntity(URLConstant.HOST_LOCK_FIND,String.class,param);
            JSONObject jsonObject=JSONObject.fromObject(JSONArray.fromObject(responseEntity.getBody()).get(0));
            Object lockId=jsonObject.get("lockId");
            MultiValueMap<String ,Object> param1=new LinkedMultiValueMap<String,Object>();
            Date date=new Date();

            JSONObject object=new JSONObject();
            object.put("openLockId",lockId);
            object.put("cmd",cmd);
            object.put("timeStamp",date.getTime());

            param1.add("secureData",AESUtil.encrypt(object.toString(),"1234fghjnmlkiuhA"));
            ResponseEntity responseEntity1=restTemplate.postForEntity(URLConstant.HOST_DEVICE_OPENLOCKID,param1,String.class);

            result=responseEntity1.getBody().toString();
            if(result.equals("1")&&"open".equals(cmd)){
                result="开锁成功";
            }else if(result.equals("1")&&"close".equals(cmd)){
                result="关锁成功";
            }
        }catch (HttpClientErrorException hce){
            result=hce.toString();
        }catch (Exception e){
            result=e.toString();
        }
        return result;
    }
}
